<template>
    <div class="course-detail" v-cloak>
        <div v-wechat-title="title"></div>
        <div class="banner"><img :src="banner"></div>
        <div class="title"><img slot="icon" src="./img/border.png" height="20"><b>{{title}} {{part}}</b></div>
        <div class="content" v-html="htmlSrc"></div>
        <!-- <div class="content"><course-content :html="htmlSrc"></course-content></div> -->
        <div v-if="material" class="view-material">
            <mt-button size="large" type="primary" @click="viewMaterial">查看教案</mt-button>
        </div>
    </div>
</template>

<script>
    // import PenguinPlayer from '@/components/PenguinPlayer.vue'
    import 'dplayer/dist/DPlayer.min.css';
    import DPlayer from 'dplayer';
    // let CourseContent = {
    //     name: 'course-content',
    //     props: ['html'],
    //     components: {
    //         'mt-range': Range
    //     },
    //     render: function(h) {
    //         return h('div', {
    //             domProps: {
    //                 innerHTML: this.html
    //             },
    //         })
    //     }
    // }
    export default {
        name: 'course-detail',
        components: {
            // CourseContent
        },
        props: ['title', 'banner', 'html', 'material', 'part'],
        data() {
            return {
                // videoRange: 0,
            }
        },
        computed: {
            htmlSrc: function() {
                return this.initMediaHtml(this.html)
            }
        },
        mounted() {
            setTimeout(function() {
                this.initMedia()
            }.bind(this), 200)
        },
        methods: {
            createDom(arg) {
                let objE = document.createElement("div")
                objE.innerHTML = arg;
                return objE.childNodes[0]
            },
            initMediaHtml(v) {
                let html = v
                let audioList = html.match(/<audio.*?\n*?.*?<\/audio>/g)
                audioList && audioList.forEach(e => {
                    /* 这什么零宽度负回顾后发断言，PC上支持，手机上不支持，查了好久，妈的！这样导致的问题就是，如果两个媒体地址一样。就会出问题，重复替换第一个 */
                    // html = html.replace(/(?<!class="audio-wrap">)<audio.*?<\/audio>/, ('<div class="audio-wrap">'+e+'</div>'))
                    html = html.replace(e, ('<span class="audio-wrap"><span class="head"></span><span class="title"></span><span class="bar"><span class="range"></span></span><span class="time"><span class="cur">00:00</span><span class="total"></span></span><span class="play"></span>' + e + '</span>'))
                })
                /* 为什么video无法match到？解：因为有可能换行 */
                let videoList = html.match(/<video.*?\n*?.*?<\/video>/g)
                videoList && videoList.forEach(e => {
                    // 获取video地址
                    let src = e.match(/<source src="(.*?)"/)[1]
                    // 获取poster
                    // let video = this.createDom(e)
                    // let canvas = document.createElement('canvas');
                    // canvas.width = video.videoWidth;
                    // canvas.height = video.videoHeight;
                    // canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                    // let poster = canvas.toDataURL('image/png');
                    html = html.replace(e, ('<div class="video-wrap" video-src="' + src + '"></div>'))
                })
                /* 零宽度正回顾手机同样不支持 */
                // let videoList = html.match(/(?<=<source src=)".*?"/g)
                return html
            },
            initMedia() {
                this.initVideo()
                this.initAudio()
            },
            initVideo() {
                document.querySelectorAll('.video-wrap').forEach(e => {
                    let url = e.getAttribute('video-src')
                    // let v = e.querySelectorAll('video')[0]
                    // v.style.display = 'none'
                    // let url = v.querySelectorAll('source')[0].src
                    // console.log(url)
                    new DPlayer({
                        container: e,
                        video: {
                            url,
                            pic: url + '?x-oss-process=video/snapshot,t_2000,m_fast'
                        }
                    })
                })
            },
            getTime(time) { //默认获取的时间是时间戳改成我们常见的时间格式
                //分钟
                let minute = time / 60;
                let minutes = parseInt(minute).toString().padStart(2, '0')
                //秒
                let second = time % 60
                let seconds = Math.round(second).toString().padStart(2, '0')
                return minutes + ":" + seconds
            },
            initAudio() {
                let _t = this
                document.querySelectorAll('.audio-wrap').forEach(e => {
                    let timeInterval;
                    let startX, x, aboveX = 0, dragging = false;
                    let audio = e.querySelectorAll('audio')[0]
                    let pBtn = e.querySelectorAll('.play')[0]
                    let range = e.querySelectorAll('.bar .range')[0]
                    let curTime = e.querySelectorAll('.time .cur')[0]
                    let totalTime = e.querySelectorAll('.time .total')[0]
                    let head = e.querySelectorAll('.head')[0]
                    let barWith = e.querySelectorAll('.bar')[0].offsetWidth - 8
                    let touchStart = function(e) {
                        e.preventDefault()
                        let touch = e.touches[0]
                        startX = touch.pageX
                        dragging = true
                    }
                    let touchMove = function(e) { //滑动          
                        e.preventDefault()
                        let touch = e.touches[0]
                        x = touch.pageX - startX //滑动的距离
                        range.style.left = aboveX + x + "px" //  
                    }

                    let touchEnd = function(e) { //手指离开屏幕
                        e.preventDefault()
                        dragging = false
                        aboveX = parseInt(range.style.left)
                        let dragPaddingLeft = range.style.left
                        let change = dragPaddingLeft.replace("px", "")
                        let numDragpaddingLeft = parseInt(change)
                        let currentTime = (numDragpaddingLeft / barWith) * audio.duration //30是拖动圆圈的长度，减掉是为了让歌曲结束的时候不会跑到window以外
                        audio.currentTime = currentTime
                    }
                    range.addEventListener("touchstart", touchStart, false)
                    range.addEventListener("touchmove", touchMove, false)
                    range.addEventListener("touchend", touchEnd, false)

                    pBtn.addEventListener('click', function() {
                        if (this.className == 'play') {
                            audio.play()
                        } else {
                            audio.pause()
                        }
                    })
                    audio.addEventListener("loadeddata", function() {
                        totalTime.innerHTML = _t.getTime(audio.duration)
                    }, false);
                    audio.addEventListener("pause", function() {
                        head.className = 'head'
                        pBtn.className = 'play'
                        clearInterval(timeInterval)
                    }, false);
                    audio.addEventListener("play", function() { //监听暂停
                        head.className = 'head playing'
                        pBtn.className = 'play stop'
                        timeInterval = setInterval(function() {
                            console.log(audio.currentTime)
                            curTime.innerHTML = _t.getTime(audio.currentTime)
                            if(!dragging){
                                range.style.left = (audio.currentTime / audio.duration) * barWith + "px"
                            }
                            aboveX = (audio.currentTime / audio.duration) * barWith
                        }, 1000);
                    }, false);
                    audio.addEventListener("ended", function() {
                        clearInterval(timeInterval)
                        if(dragging){
                            return false
                        }
                        curTime.innerHTML = _t.getTime(audio.duration)
                        range.style.left = barWith + "px";
                        aboveX = 0
                        setTimeout(function() {
                            curTime.innerHTML = '00:00'
                            range.style.left = '-7px';
                            pBtn.className = 'play'
                            head.className = 'head'
                        }, 500)
                    }, false)

                })
            },
            addListenTouch(au) {
                //touchstart,touchmove,touchend事件函数
                let startX, x, aboveX = 0;
                let drag = au.querySelectorAll('.bar .range')[0]
                let audio = au.querySelectorAll('audio')[0]
                let barWith = au.querySelectorAll('.bar')[0].offsetWidth - 8

                
                // audio.addEventListener("play", function() { //监听暂停
                //     setInterval(function() {
                //         console.log(audio.currentTime)
                //         curTime.innerHTML = _t.getTime(audio.currentTime)
                //         range.style.left = (audio.currentTime / audio.duration) * barWith + "px";
                //     }, 1000);
                // }, false);
                audio.addEventListener("ended", function() {
                    aboveX = 0
                }, false)
            },


            viewMaterial() {
                let material = {
                    name: this.title,
                    content: this.material,
                    part: this.part
                }
                window.sessionStorage.setItem('materialInfo', JSON.stringify(material));
                this.$router.push('/material')
            }
        },
    }
</script>

<style scoped lang="scss">
    .course-detail {
        .banner {
            text-align: center;

            img {
                display: inline-block;
                width: 100%;
                max-height: 2rem;
            }
        }

        .title {
            padding: .15rem .1rem .08rem;
            font-size: 16px;
            color: var(--deepColor);
            height: 26px;
            line-height: 26px;
            font-size: 16px;
            border-bottom: solid 1px var(--borderColor);
            white-space: nowrap;
            overflow: hidden;

            .part {
                font-size: 14px;
            }

            img {
                float: left;
                margin-right: 5px;
                margin-top: 2px;
            }
        }

        .content {
            padding: .15rem .1rem;

            img {
                max-width: 100%;
            }
        }

        .view-material {
            position: fixed;
            bottom: 0;
            width: 100%;

            /deep/ .mint-button--large {
                border-radius: 0;
            }
        }

        /deep/ {
            .video-wrap {
                width: 100%;
            }

            .audio-wrap {
                display: inline-block;
                width: 300px;
                height: 55px;
                position: relative;
                background: url(./img/player_back.png) no-repeat;
                background-size: contain;

                audio {
                    visibility: hidden;
                }

                >span {
                    display: block;
                    position: absolute;
                }

                @keyframes headRound {
                    from {
                        transform: rotate(0deg);
                    }

                    to {
                        transform: rotate(360deg);
                    }
                }

                .head {
                    width: 34px;
                    height: 34px;
                    left: 22px;
                    top: 50%;
                    margin-top: -17px;
                    border-radius: 50%;
                    background: url(./img/player_head.png) no-repeat;
                    background-size: cover;
                    animation: headRound 5s linear infinite;
                    animation-play-state: paused;

                    &.playing {

                        animation-play-state: running;
                    }
                }

                .bar {
                    height: 2px;
                    width: 57%;
                    // background: #fff;
                    left: 24%;
                    top: 50%;

                    .range {
                        position: absolute;
                        display: block;
                        left: -8px;
                        top: -7px;
                        background: url(./img/player_range.png) no-repeat;
                        background-size: cover;
                        width: 16px;
                        height: 16px;
                        border-radius: 50%;
                    }
                }

                .time {
                    bottom: 4px;
                    left: 22%;
                    width: 59%;
                    font-size: 12px;
                    color: #fff;

                    .cur {
                        float: left;
                    }

                    .total {
                        float: right;
                    }
                }

                .play {
                    width: 36px;
                    height: 36px;
                    right: 10px;
                    top: 50%;
                    transform: translateY(-16px);
                    border-radius: 50%;
                    background: url(./img/player_play.png) no-repeat;
                    background-size: cover;

                    &.stop {
                        background-image: url(./img/player_pause.png)
                    }
                }
            }
        }


    }
</style>